const { connection } = require('../connect/connect')
var async = require("./async.js");
var url = require('url');
var util = require('util');
var jwt = require("jsonwebtoken");
var md5 = require("md5");
//注册
exports.register = function (req, res) {
    // console.log(req);
    let params = req.body;
    let password = params.password;
    let email = params.email;
	let userName = params.name;
    connection.query("select * from user where email='" + email + "'", function (erro, result) {
        if (erro) {
            console.log(erro)
            res.sendStatus(403);
        } else {
			if(result.length) {
				res.send({
                    code:1,
                    message: '账户已存在'
                });
			} else {
				connection.query(`insert into user set name=${userName},created_at=${new Date().getTime()},email="${email}",is_locked=${0},updated_at=${new Date().getTime()},password=${password}`, function (erro, result) {
				    if (erro) {
				        console.log(erro)
				        res.status(500).send({
				            code: 1,
				            message: '注册失败！' + erro,
				        });
				    } else {
						res.send({
						    code:0,
						    message: '注册成功！'
						});
					}
				})
				
			}
		}
    })
}
//登录
exports.login = function (req, res) {
    // console.log(req);
    let params = req.body;
    let password = params.password;
    let email = params.email;
    connection.query("select * from user where password='" + password + "'" + " and email='" + email + "'", function (erro, result) {
        if (erro) {
            console.log(erro)
            res.sendStatus(403);
        }
        var user = {
            "jti": 1,
            "iss": "admin",
            "user": email,
            "password": password,
            'user_id': result[0].id
        }
        jwt.sign(user, "seretkey", { expiresIn: "1day" }, function (err, token) {
            res.json({ access_token: token });
        });
        // res.send(result);
    })
}
//用户信息
exports.user = function (req, res) {
    jwt.verify(req.headers.authorization, "seretkey", function (err, authData) {
        if (err) {
            res.sendStatus(401);
        } else {
            console.log(authData);
            let email = authData.user
            let password = authData.password
            connection.query("select * from user where password='" + password + "'" + " and email='" + email + "'", function (erro, result) {
                if (erro) {
                    console.log(erro)
                    res.sendStatus(401);
                }
                res.send(result[0]);
            })
            // res.json(authData)
        }
    })
}
//修改昵称
exports.reviseUser = function (req, res) {
    jwt.verify(req.headers.authorization, "seretkey", function (err, authData) {
        if (err) {
            res.sendStatus(401);
        } else {
            console.log(authData);
            if (req.body.name) {
                let email = authData.user
                let password = authData.password
                let name = req.body.name
                connection.query(`update user set name='${name}' where password='${password}' and email='${email}'`, function (erro, result) {
                    if (erro) {
                        console.log(erro)
                        res.status(500).send({
                            code: 1,
                            message: '修改失败！' + erro,
                        });
                    }
                    res.send({
                        code: 0,
                        message: '修改成功！'
                    });
                })
            }

            // res.json(authData)
        }
    })
}
//上传头像
exports.uploadAvatar = function (req, res) {
    jwt.verify(req.headers.authorization, "seretkey", function (err, authData) {
        if (err) {
            res.sendStatus(401);
        } else {
            console.log(authData);
			let params = url.parse(req.url, true).query;
            
            res.json(authData)
        }
    })
}
//主页列表
exports.index = function (req, res) {
    // console.log('/api/sellShow/mysell')
    let params = url.parse(req.url, true).query;
    // console.log(params,'-----')
    // console.log(typeof(params),'++++++')
    if (JSON.stringify(params) === '{}') {
        // console.log(req.url)
        connection.query('select * from slides', function (erro, result) {
            // console.log(result)
            let resul = {
                slides: result
            }
            res.send(resul)
        })
    }
    if (params.page != null) {
        let resul = {}
        let SQL = `select * from goods limit ${(params.page - 1) * 10},10;select * from slides`
        connection.query(SQL, function (erro, result) {
            // console.log(result)
            resul.goods = {
                data: result[0]
            }
            resul.slides = result[1]
            res.send(resul)
        })

    }

}
//商品详情
exports.goodsDetail = function (req, res) {
    // console.log('/api/sellShow/mysell')
    let params = url.parse(req.url, true).query;
    // console.log(params,'-----')
    // console.log(req.params.aid);
    // console.log(typeof(params),'++++++')
    if (JSON.stringify(params) === '{}') {
        // console.log(req.url)
        connection.query(`select * from goods where id=${req.params.aid}`, function (erro, result) {
            let resul = {
                goods: result[0]
            }
            // console.log(resul);
            res.send(resul)
        })
    }
}
//商品列表
exports.goods = function (req, res) {
    // console.log('/api/sellShow/mysell')
    let params = url.parse(req.url, true).query;
    // console.log(params,'-----')
    // console.log(req.params.aid);
    // console.log(typeof(params),'++++++')
    if (JSON.stringify(params) === '{}') {
        // console.log(req.url)
        connection.query(`select * from categories`, function (erro, result) {
            let resul = {
                categories: result
            }
            // console.log(resul);
            res.send(resul)
        })
    }
    if (params.page != null) {
        let SQL = ""
        if (params.category_id != '' && params.category_id != null) {
            SQL = `select * from goods where category_id=${params.category_id} limit ${(params.page - 1) * 10},10;select * from slides;select * from categories where level=1`
        } else {
            SQL = `select * from goods where category_id=1 limit ${(params.page - 1) * 10},10;select * from slides;select * from categories where level=1`
        }
        connection.query(SQL, function (erro, result) {
            // console.log(result)
            let resul = {}
            resul.goods = {
                data: result[0]
            }
            resul.slides = result[1]
            async.map(result[2], function (item, callback) {
                connection.query(`select * from categories where no=${item.no + 1}`, function (erro, result) {
                    item.children = result
                    callback(null, item)
                })
            }, function (err, categories) {
                resul.categories = categories
                res.send(resul)
            })
        })
    }

}
//购物车列表
exports.carts = function (req, res) {
    let params = url.parse(req.url, true).query;
    let sql = 'select * from carts';
    connection.query(sql, function (err, result) {
        if (err) {
            res.status(500).send({
                code: 1,
                message: err,
            });
        } else {
            async.map(result, function (item, callback) {
                connection.query(`select * from goods where id=${item.goods_id}`, function (err, result) {
                    if (err) {
                        res.status(500).send({
                            code: 1,
                            message: err,
                        });
                    } else {
                        item.goods = result[0]
                        callback(null, item)
                    }
                    
                })
            }, function (err, data) {
                res.send({
                    code:0,
                    data,
                    message:'成功'
                })  
            })  
        }
    })
}
//加入购物车
exports.addCarts = function (req, res) {
    let params = url.parse(req.url, true).query;
    jwt.verify(req.headers.authorization, "seretkey", function (err, authData) {
        if (err) {
            res.sendStatus(401);
        } else {
            connection.query(`select * from carts where goods_id=${req.body.goods_id}`, function (err, result) {
                if (err) {
                    res.status(500).send({
                        code: 1,
                        message: err,
                    });
                } else {
                    if(result.length>0){
                        connection.query(`update carts set num=${result[0].num + 1} where goods_id=${req.body.goods_id}`, function (err, result) {
                            if (err) {
                                res.status(500).send({
                                    code: 1,
                                    message: err,
                                });
                            } else {
                                    res.send({
                                        code:0,
                                        message: '成功'
                                    })   
                            }
                        })
                    } else {
                        let sql = `insert into carts set num=1,is_checked=0,goods_id=${req.body.goods_id},user_id=${authData.user_id}`;
                        connection.query(sql, function (err, result) {
                            if (err) {
                                res.status(500).send({
                                    code: 1,
                                    message: err,
                                });
                            } else {
                                    res.send({
                                        code:0,
                                        message: '成功'
                                    })   
                            }
                        })
                    }
                }
            })
            
        }
    })
    
}
//更改购物车数量
exports.setCartsNum = function (req, res) {
    let params = url.parse(req.url, true).query;
    let sql = `update carts set num=${req.body.num} where id=${req.params.aid}`;
    connection.query(sql, function (err, result) {
        if (err) {
            res.status(500).send({
                code: 1,
                message: err,
            });
        } else {
                res.send({
                    code:0,
                    message: '成功'
                })   
        }
    })
}
//移除购物车
exports.removeCarts = function (req, res) {
    let params = url.parse(req.url, true).query;
    let sql = `delete from carts where id=${req.params.aid}`;
    connection.query(sql, function (err, result) {
        if (err) {
            res.status(500).send({
                code: 1,
                message: err,
            });
        } else {
                res.send({
                    code:0,
                    message: '成功'
                })   
        }
    })
}
//更改选中状态
exports.setCartsChecked = function (req, res) {
    let params = url.parse(req.url, true).query;
    connection.query(`update carts set is_checked=0;`, function (err, result) {
        if (err) {
            res.status(500).send({
                code: 1,
                message: err,
            });
        } else {
            async.map(req.body.cart_ids, function (item, callback) {
                    connection.query(`update carts set is_checked=1 where id=${item}`, function (err, result) {
                        if (err) {
                            res.status(500).send({
                                code: 1,
                                message: err,
                            });
                        } else {
                            callback(null, result[1])
                        }
                    })
                }, function (err, data) {
                    if (err) {
                        res.status(500).send({
                            code: 1,
                            message: err,
                        });
                    } else {
                            res.send({
                                code:0,
                                data,
                                message: '成功'
                            })   
                    }
                }) 
        }
    })
    
    
}
//收藏
exports.collects = function (req, res) {
    let params = url.parse(req.url, true).query;
    let sql = 'select * from collects';
    connection.query(sql, function (err, result) {
        if (err) {
            res.status(500).send({
                code: 1,
                message: err,
            });
        } else {
            let goods = []
            async.map(result, function (item, callback) {
                connection.query(`select * from goods where id=${item.goods_id}`, function (erro, result) {
                    if (err) {
                        res.status(500).send({
                            code: 1,
                            message: err,
                        });
                    } else {
                        item.goods = result[0]
                        callback(null, item)
                    }
                    
                })
            }, function (err, data) {
                res.send({
                    data
                })  
            })
            
        }
    })
}
//添加收藏
exports.addCollects = function (req, res) {
    let params = url.parse(req.url, true).query;
    jwt.verify(req.headers.authorization, "seretkey", function (err, authData) {
        if (err) {
            res.sendStatus(401);
        } else {
            connection.query('select * from collects where goods_id=' + req.params.aid, function (err, result) {
                if(err){
                    res.status(500).send({
                        code: 1,
                        message: err,
                    });
                } else{
                    if(result.length>0){
                       connection.query(`delete from collects where goods_id=${req.params.aid};update goods set is_collect=0 where id=${req.params.aid};`, function (err, result) {
                        if (err) {
                            res.status(500).send({
                                code: 1,
                                message: err,
                            });
                        } else{
                            res.send({
                                code: 0,
                                message: '取消收藏',
                            });
                        }
                        }) 
                    } else{
                        let sql = `insert into collects set goods_id=${req.params.aid},created_at='${new Date().getTime()}',user_id='${authData.user_id}';update goods set is_collect=1 where id=${req.params.aid};`;
                        connection.query(sql, function (err, result) {
                            if (err) {
                                res.status(500).send({
                                    code: 1,
                                    message: err,
                                });
                            } else {
                                res.send({
                                    code: 0,
                                    message: '收藏成功！',
                                });
                            }
                        })
                    }
                    
                }
            })
        }
    })
    
}
//收货地址
exports.address = function (req, res) {
    let params = url.parse(req.url, true).query;
    let sql = 'select * from address';
    connection.query(sql, function (err, result) {
        if (err) {
            res.status(500).send({
                code: 1,
                message: err,
            });
        } else {
            res.send({
                data: result
            })
        }
    })
}
//获取地址
exports.addAddress = function (req, res) {
    let { address, city, county, is_default, name, phone, 
        province } = req.body
    let sql = `insert into address set address='${address}',county='${county}',
    created_at='${new Date().getTime()}',is_default=${is_default ? 1 : 0},name='${name}',
    phone=${phone},province='${province}',city='${city}'`;
    connection.query(sql, function (err, result) {
        if (err) {
            res.status(500).send({
                code: 1,
                message: err,
            });
        } else {
            res.send({
                code:0,
                message:'新增地址成功！'
            })
        }
    })
}
//更改地址
exports.updateAddress = function (req, res) {
    let params = url.parse(req.url, true).query;
    let { address, city, county, created_at, is_default, name, phone, 
        province, updated_at } = req.body
    let sql = `update address set address='${address}',county='${county}',
    created_at='${created_at}',updated_at='${updated_at}',is_default=${is_default ? 1 : 0},name='${name}',
    phone=${phone},province='${province}',city='${city}',county='${county}' where id=${req.params.aid}`;
    connection.query(sql, function (err, result) {
        if (err) {
            res.status(500).send({
                code: 1,
                message: err,
            });
        } else {
            res.send({
                data: result
            })
        }
    })
}
//删除地址
exports.removeAddress = function (req, res) {
    let sql = `delete from address where id=${req.params.aid}`;
    connection.query(sql, function (err, result) {
        if (err) {
            res.status(500).send({
                code: 1,
                message: err,
            });
        } else {
            res.send({
                code: 0,
                message: '删除成功！',
            })
        }
    })
}

//订单预览
exports.preview = function (req, res) {
    let params = url.parse(req.url, true).query;
    let sql = 'select * from carts';
    connection.query(sql, function (err, result) {
        if (err) {
            res.status(500).send({
                code: 1,
                message: err,
            });
        } else {
            async.map(result, function (item, callback) {
                connection.query(`select * from goods where id=${item.goods_id}`, function (err, result) {
                    if (err) {
                        res.status(500).send({
                            code: 1,
                            message: err,
                        });
                    } else {
                        item.goods = result[0]
                        callback(null, item)
                    }
                    
                })
            }, function (err, data) {
                res.send({
                    code:0,
                    carts:data,
					address:[],
                    message:'成功'
                })  
            })  
        }
    })
}
//添加订单
exports.orders = function (req, res) {
    let params = req.body;
	console.log(req)
    jwt.verify(req.headers.authorization, "seretkey", function (err, authData) {
        if (err) {
            res.sendStatus(401);
        } else {
            connection.query('select * from address where id=' + params.address_id, function (err, result) {
                if(err){
                    res.status(500).send({
                        code: 1,
                        message: err,
                    });
                } else{
                    if(result.length>0){
                       connection.query(`insert into orders set address_id=${params.address_id},user_id=${authData.user_id},status=${0},created_at=${new Date().getTime()},updated_at=${new Date().getTime()}`, function (err, result) {
                        if (err) {
                            res.status(500).send({
                                code: 1,
                                message: err,
                            });
                        } else{
							connection.query(`select * from orders where address_id=${params.address_id} and user_id=${authData.user_id}`, function (err, result) {
								if(err) {
									res.status(500).send({
									    code: 1,
									    message: err,
									});
								} else {
									res.send({
										code: 0,
										order_no:result,
										message: '添加成功',
									});
								}
							})
                        }
                        }) 
                    } else{
                        
                    }
                    
                }
            })
        }
    })
    
}



exports.getUser = function (req, res) {
    let params = url.parse(req.url, true).query;
    let password = params.password;
    let mobile = params.iphone;
    connection.query("select * from user where password='" + password + "'" + " and iphone='" + mobile + "'", function (erro, result) {
        if (erro) {
            console.log(erro)
            res.send(erro)
        }
        res.send(result);
    })
}


exports.insertUser = function (req, res) {
    // console.log('.........')
    let params = req.body;
    let username = params.username;
    let password = params.password;
    let iphone = params.iphone;
    let addparams = [username, password, iphone];
    let sql2 = 'insert into user(user_name,password,iphone) values(?,?,?)';
    connection.query("select * from user where user_name=" + "'" + username + "'" + " or iphone=" + iphone
        , function (err, result) {
            if (JSON.stringify(result) === '[]') {
                console.log('select * from user where user_name=' + username)
                connection.query(sql2, addparams, function (err, result) {
                    if (err) {
                        // res.send(err);
                    } else {
                        res.send([]);
                    }
                })
            } else {
                console.log("select * from user where user_name=" + "'" + username + "'")
                res.send(result);
            }
        })
}
exports.insertCollect = function (req, res) {
    let params = url.parse(req.url, true).query;
    let usernameId = params.usernameId;
    let bookId = params.bookId;
    let sql = 'select * from user_collect where user_id=' + usernameId + ' and book_id=' + bookId;
    let sql2 = 'insert into user_collect(user_id,book_id) values(?,?)'
    let params_data = [usernameId, bookId]
    connection.query(sql, function (err, result) {
        if (JSON.stringify(result) === '[]') {
            console.log('插入收藏区', usernameId, bookId)
            connection.query(sql2, params_data, function (err, result2) {
                if (err) {
                    res.send(err)
                } else {
                    res.send('收藏成功');
                }
            })
            // res.send(false)//没有收藏
        } else {
            console.log('select * from user_collect where user_id=' + usernameId + ' and book_id=' + bookId)
            console.log('已收藏区', usernameId, bookId)
            res.send(true)
        }
    })
}


